<?php
/*******************************************************************************
 * Copyright 2009-2014 Amazon Services. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 *
 * You may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
 * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 
 * specific language governing permissions and limitations under the License.
 *******************************************************************************
 * PHP Version 5
 * @category Amazon
 * @package  Marketplace Web Service Orders
 * @version  2011-01-01
 * Library Version: 2014-10-20
 * Generated: Fri Oct 17 15:37:50 GMT 2014
 */

/**
 * List Orders Sample
 */
 $key=trim($_GET['key']);
require_once($key.'.config.inc.php');
require_once '../../../config/common_config.php';
require_once PATH_ROOT.'/inc/global.php';
$db = createMysqlDbLink($mysql_config["of"]);

 ini_set('display_errors', 1);
/************************************************************************
 * Instantiate Implementation of MarketplaceWebServiceOrders
 *
 * AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY constants
 * are defined in the .config.inc.php located in the same
 * directory as this sample
 ***********************************************************************/
// More endpoints are listed in the MWS Developer Guide
// North America:
//$serviceUrl = "https://mws.amazonservices.com/Orders/2011-01-01";
// Europe
//$serviceUrl = "https://mws-eu.amazonservices.com/Orders/2011-01-01";
// Japan
//$serviceUrl = "https://mws.amazonservices.jp/Orders/2011-01-01";
// China
//$serviceUrl = "https://mws.amazonservices.com.cn/Orders/2011-01-01";


 $config = array (
   'ServiceURL' => $serviceUrl,
   'ProxyHost' => null,
   'ProxyPort' => -1,
   'ProxyUsername' => null,
   'ProxyPassword' => null,
   'MaxErrorRetry' => 3,
 );

 $service = new MarketplaceWebServiceOrders_Client(
        AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY,
        APPLICATION_NAME,
        APPLICATION_VERSION,
        $config);

$count=$db->getValue("select count(*) from `amorderlist` where `ostat`=1 and `key` like '$key' limit 1");   //获取未执行任务个数

if($count>0){   //未执行任务数大于0
	$sql="select * from `amorderlist` where `ostat`=1 and `key` like '$key' limit 1";
	$query=$db->query($sql);
	$arr=$db->fetchrow($query);
	$order=json_decode($arr['detail'],true);
	$type = $arr['type'];
	$stat = $arr['stat'];
	$comefrom = $arr['comefrom'];
	$request = new MarketplaceWebServiceOrders_Model_ListOrderItemsRequest();
	$request->setSellerId(MERCHANT_ID);
	$request->setAmazonOrderId($order['AmazonOrderId']);
	$order['detail']=invokeListOrderItems($service, $request);
	$ordernum = $order['AmazonOrderId'];
	$shipping_add	= $order['ShippingAddress']['Name']."<br>".$order['ShippingAddress']['AddressLine1']."<br>".$order['ShippingAddress']['City'].",".$order['ShippingAddress']['StateOrRegion'].",".$order['ShippingAddress']['CountryCode']."<br>".$order['ShippingAddress']['PostalCode']."<br>".$order['ShippingAddress']['Phone'];
	if(is_array($order['detail'][0])){
		foreach($order['detail'] as $os){
			$skus[] = $os['SellerSKU'];
			$picture="<img width=\"150px\" height=\"150px\" src=\"../img/".get_pic($os['SellerSKU'])."\" />";
			$qc=($os['QuantityOrdered']==1)?"":"style=\"color:red\"";
			$details[]	= "<table border=\"1px\" class=\"detail_talbe\" bordercolor=\"#666666\"><tr><td rowspan=\"4\">".$picture."</td><td colspan=\"2\">".addslashes($os['Title'])."</td></tr><tr><td ".$qc.">Quantity:</td><td ".$qc.">".$os['QuantityOrdered']."</td></tr><tr><td>SKU:</td><td>".$os['SellerSKU']."</td></tr><tr><td>Order-Item ID:</td><td>".$os['OrderItemId']."</td></tr></table>";
			
		}
		$sku=implode("<br>",$skus);
		$detail=implode("<br>",$details);
		
	}else{
	$sku  		= $order['detail']['SellerSKU'];
	$picture="<img width=\"150px\" height=\"150px\" src=\"../img/".get_pic($sku)."\" />";
	$qc=($order['detail']['QuantityOrdered']==1)?"":"style=\"color:red\"";
	$detail		= "<table border=\"1px\" class=\"detail_talbe\" bordercolor=\"#666666\"><tr><td rowspan=\"4\">".$picture."</td><td colspan=\"2\">".addslashes($order['detail']['Title'])."</td></tr><tr><td ".$qc.">Quantity:</td><td ".$qc.">".$order['detail']['QuantityOrdered']."</td></tr><tr><td>SKU:</td><td>".$sku."</td></tr><tr><td>Order-Item ID:</td><td>".$order['detail']['OrderItemId']."</td></tr></table>";
	
	}
	$addtime	   	= date("Y-m-d h:i:s",time());
	$paymentdate		= date("Y-m-d h:i:s",strtotime($order['PurchaseDate']));
	$trackid		= "";

if(($type=="")||($comefrom=="")||($ordernum=="")||($shipping_add=="")||($detail=="")||($stat=="")||($addtime==""))
{
	echo ("<h1>信息不完整，一分钟后重新执行本任务。。</h1>");
	echo "<script>	function refreshPage() { window.location.reload(); } window.setTimeout('refreshPage()',60000);</script>";
}
$is_dup=$db->getValue("select count(*) from `orders` where `ordernum`='$ordernum'");    //查询该订单是否已经录入
if($is_dup>0){   //录入过的订单更新状态
	$sql = "update `orders` set `types`='$type' ,`comefrom`='$comefrom' ,`ordernum`='$ordernum' ,`sku`='$sku',`shipping_add`='$shipping_add' ,`detail`='$detail' , `adddt`='$addtime' ,`paymentdate`='$paymentdate' where `ordernum` like '$ordernum'";
	$flag=$db->query($sql);
		if($flag){
				$order_id=$db->getvalue("select id from `orders` where `ordernum`='$ordernum' ");
				$memo1="操作者:SYSTEM <br>操作时间:".$addtime."<br>操作备注:修改订单。";
				$sqlx = "insert into `order_info` (`order_id`,`action`)values($order_id,'$memo1')";
				$db->query($sqlx);
				if(is_array($order['detail'][0])){ //一单多件
					$pris=array();
					foreach($order['detail'] as $os){
					$price = $os['ItemPrice'];
					if($price['CurrencyCode']=='USD') $pris[]="$".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']+$os['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='GBP') $pris[]="£".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']+$os['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='EUR') $pris[]="€".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']+$os['ShippingDiscount']['Amount']);
					updatequantity($ordernum,$os['SellerSKU'],$os['QuantityOrdered']);
					}
					$pri=implode(",",$pris);
					$db->query("update`order_price` set`oid`=$order_id,`price`='$pri' where `oid` like '$order_id'");
					
				}else{  //一单一件
					$price = $order['detail']['ItemPrice'];
					if($price['CurrencyCode']=='USD') $pri="$".($price['Amount']+$order['detail']['ShippingPrice']['Amount']+$order['detail']['GiftWrapPrice']['Amount']+$order['detail']['ItemTax']['Amount']+$order['detail']['ShippingTax']['Amount']+$order['detail']['GiftWrapTax']['Amount']+$order['detail']['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='GBP') $pri="£".($price['Amount']+$order['detail']['ShippingPrice']['Amount']+$order['detail']['GiftWrapPrice']['Amount']+$order['detail']['ItemTax']['Amount']+$order['detail']['ShippingTax']['Amount']+$order['detail']['GiftWrapTax']['Amount']+$order['detail']['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='EUR') $pri="€".($price['Amount']+$order['detail']['ShippingPrice']['Amount']+$order['detail']['GiftWrapPrice']['Amount']+$order['detail']['ItemTax']['Amount']+$order['detail']['ShippingTax']['Amount']+$order['detail']['GiftWrapTax']['Amount']+$order['detail']['ShippingDiscount']['Amount']);
					$db->query("update`order_price` set`oid`=$order_id,`price`='$pri' where `oid` like '$order_id'");
					updatequantity($ordernum,$order['detail']['SellerSKU'],$order['detail']['QuantityOrdered']);
				}
			echo $ordernum." update success!<br>";
			$db->query("update `amorderlist` set `ostat`=0 where `ordernum` like '$ordernum'");
		}else{
			echo $ordernum." update failure!<br>";
		}
}else{     //新订单录入
	$sql = "INSERT INTO  `orders` (`types` ,`comefrom` ,`ordernum` ,`sku`,`shipping_add` ,`detail` ,`stat` ,`adddt` ,`paymentdate`,`trackid`)VALUES (  '$type',  '$comefrom',  '$ordernum', '$sku', '$shipping_add',  '$detail',  '$stat',  '$addtime', '$paymentdate', '$trackid')";

	$flag=$db->query($sql);
	
		if($flag){
				$order_id=$db->getvalue("select max(id) from `orders`");
				$memo1="操作者:SYSTEM <br>操作时间:".$addtime."<br>操作备注:提交订单。";
				$sqlx = "insert into `order_info` (`order_id`,`action`)values($order_id,'$memo1')";
				$db->query($sqlx);
				if(is_array($order['detail'][0])){
					$pris=array();
					foreach($order['detail'] as $os){
					$price = $os['ItemPrice'];
					if($price['CurrencyCode']=='USD') $pris[]="$".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']+$os['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='GBP') $pris[]="£".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']+$os['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='EUR') $pris[]="€".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']+$os['ShippingDiscount']['Amount']);
					updatequantity($ordernum,$os['SellerSKU'],$os['QuantityOrdered']);
					}
					$pri=implode(",",$pris);
					$db->query("insert into `order_price` (`oid`,`price`)values($order_id,'$pri')");
				}else{
				$price = $order['detail']['ItemPrice'];
				if($price['CurrencyCode']=='USD') $pri="$".($price['Amount']+$order['detail']['ShippingPrice']['Amount']+$order['detail']['GiftWrapPrice']['Amount']+$order['detail']['ItemTax']['Amount']+$order['detail']['ShippingTax']['Amount']+$order['detail']['GiftWrapTax']['Amount']+$order['detail']['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='GBP') $pri="£".($price['Amount']+$order['detail']['ShippingPrice']['Amount']+$order['detail']['GiftWrapPrice']['Amount']+$order['detail']['ItemTax']['Amount']+$order['detail']['ShippingTax']['Amount']+$order['detail']['GiftWrapTax']['Amount']+$order['detail']['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='EUR') $pri="€".($price['Amount']+$order['detail']['ShippingPrice']['Amount']+$order['detail']['GiftWrapPrice']['Amount']+$order['detail']['ItemTax']['Amount']+$order['detail']['ShippingTax']['Amount']+$order['detail']['GiftWrapTax']['Amount']+$order['detail']['ShippingDiscount']['Amount']);
				$db->query("insert into `order_price` (`oid`,`price`)values($order_id,'$pri')");
				updatequantity($ordernum,$order['detail']['SellerSKU'],$order['detail']['QuantityOrdered']);
				}
				$db->query("update `amorderlist` set `ostat`=0 where `ordernum` like '$ordernum'");
			echo $ordernum." insert success!<br>";
			//宅急送自动更新开始
			$CountryKey=$order['ShippingAddress']['CountryCode'];
			if($CountryKey=="GB"||$CountryKey=="DE"||$CountryKey=="IT"||$CountryKey=="FR"||$CountryKey=="ES"){
				$serverURL="http://order.zjs.com.cn/default/svc/wsdl";
				$appToken="b93b5ce51bbd05ba2e89cb3837ecbb31";
				$appKey="b93b5ce51bbd05ba2e89cb3837ecbb318d37c57f3976784a7137dd7d1763a5fd";
				$service="createOrder";

				$Consignee['consignee_province']=$order['ShippingAddress']['StateOrRegion'];
				$Consignee['consignee_city']=$order['ShippingAddress']['City'];
				$Consignee['consignee_street']=$order['ShippingAddress']['AddressLine1'];
				$Consignee['consignee_postcode']=$order['ShippingAddress']['PostalCode'];
				$Consignee['consignee_name']=$order['ShippingAddress']['Name'];
				$Consignee['consignee_telephone']=$order['ShippingAddress']['Phone'];

				$Shipper['shipper_countrycode']="CN";
				$Shipper['shipper_province']="Fujian";
				$Shipper['shipper_city']="Xiamen";
				$Shipper['shipper_street']="23-1106 lianfaxinyueyuan";
				$Shipper['shipper_postcode']="361000";
				$Shipper['shipper_name']="Yong Hu";
				$Shipper['shipper_telephone']="8613616020502";
				$Shipper['shipper_mobile']="8613616020502";

				$ItemArr['invoice_enname']="legging";
				$ItemArr['invoice_quantity']="1";
				$ItemArr['invoice_unitcharge']="2";

				$paramsJson['reference_no']=$ordernum;
				$paramsJson['shipping_method']="NLXBGH";
				$paramsJson['country_code']=$order['ShippingAddress']['CountryCode'];


			
		$consignee = array(
						'consignee_company' =>'',
						'consignee_province' =>$Consignee['consignee_province'],
						'consignee_name' =>$Consignee['consignee_name'],
						'consignee_city' =>$Consignee['consignee_city'],
						'consignee_telephone' =>$Consignee['consignee_telephone'],
						'consignee_mobile' =>'',
						'consignee_postcode' =>$Consignee['consignee_postcode'],
						'consignee_email' =>'',
						'consignee_street' =>$Consignee['consignee_street'],
						'consignee_certificatetype' =>'',
						'consignee_certificatecode' =>'',
						'consignee_credentials_period' =>'',
				);
		$shipper = array(
						// 'shipper_account' =>'',
						'shipper_name' =>$Shipper['shipper_name'],
						'shipper_company' =>'',
						'shipper_countrycode' =>$Shipper['shipper_countrycode'],
						'shipper_province' =>$Shipper['shipper_province'],
						'shipper_city' =>$Shipper['shipper_city'],
						'shipper_street' =>$Shipper['shipper_street'],
						'shipper_postcode' =>$Shipper['shipper_postcode'],
						'shipper_areacode' =>'',
						'shipper_telephone' =>$Shipper['shipper_telephone'],
						'shipper_mobile' =>$Shipper['shipper_mobile'],
						'shipper_email' =>'',
						'shipper_fax' =>'',
				);
		$itemArr = array();
		$itemArr[] = array(
            			'invoice_enname' => $ItemArr['invoice_enname'],
            			'invoice_cnname' => '',
            			'unit_code' => '',
            			'invoice_quantity' =>$ItemArr['invoice_quantity'],
            			'invoice_unitcharge' => $ItemArr['invoice_unitcharge'],
            			'invoice_currencycode' => 'USD',
            			'hs_code' => '',
            			'invoice_note' => '',
            			'invoice_url' => ''
            	);
		$params = array(
				'shipping_method' => $paramsJson['shipping_method'],
				'country_code' => $paramsJson['country_code'],
				'reference_no'=>$paramsJson['reference_no'],
				'shipping_method_no' => '',
				'order_weight' => '10',
				'order_pieces' => '10',
				'buyer_id' => 'ddddd',
				'order_create_code' => 'w',
				'customer_id' => '',
				//'creater_id' => Service_User::getUserId (),
				'modify_date' => date ( 'Y-m-d H:i:s' ),
				'mail_cargo_type' => '1',
				//'tms_id' => Service_User::getTmsId (),
				//'customer_channelid' => Service_User::getChannelid (),
				
				'extra_service'=>'10;5Y',
				'insurance_value'=>'100',
				'Consignee' => $consignee,
				'Shipper' => $shipper,
				'ItemArr' => $itemArr
		);
		$req = array(
				'service' => 'createOrder',
				'paramsJson' => json_encode($params)
		);
        $req['appToken'] = $appToken;
        $req['appKey'] = $appKey;
// 		print_r($req);exit;
        // 超时
        $timeout = 1000;
        
        $streamContext = stream_context_create ( array (
        		'ssl' => array (
        				'verify_peer' => false,
        				'allow_self_signed' => true
        		),
        		// 'bindto' => $wmsConfig['3part']['BindTo'],
        		'socket' => array ()
        ) );
        
        
        $options = array (
        		"trace" => true,
        		"connection_timeout" => $timeout,
        		// "exceptions" => true,
        		// "soap_version" => SOAP_1_1,
        		// "features" => SOAP_SINGLE_ELEMENT_ARRAYS,
        		// "stream_context" => $streamContext,
        		"encoding" => "utf-8"
        );
        $wsdl = $serverURL; 
        function updateordernumber($retry){
			global $wsdl,$options,$req,$db;
        $client = new SoapClient ( $wsdl, $options );
        $result = $client->callService($req);
        $detail=json_decode($result->response,true);
		if($detail['ask']=="Success"){   //创建成功
			$onum=$detail['reference_no'];
			$tracknum=$detail['shipping_method_no'];
			$db->query("update `orders` set `trackid`='$tracknum' where `ordernum` like '$onum'");
		}else{
			echo "生成失败，重试中。。";
			$retry--;
			updateordernumber($retry);
		}
		}
		updateordernumber(3);
		//宅急送自动更新结束
			}
		}else{
			echo $ordernum." insert failure!<br>";
		}
}
echo "<script>function refreshPage() { window.location.reload(); } window.setTimeout('refreshPage()',3000);</script>";    //完成一个任务等3秒执行下一个任务
}else{   //没有未执行任务
	echo "Mission Complete!";
	echo "<script>window.location.href='http://www.haixing001.com/admin/MarketplaceWebServiceOrders/amapi/GetOrderList.php'</script>";
	exit;
}

function invokeListOrderItems(MarketplaceWebServiceOrders_Interface $service, $request)
  {
      try {
        $response = $service->ListOrderItems($request);

        //echo ("Service Response\n");
        //echo ("=============================================================================\n");

        $dom = new DOMDocument();
        $dom->loadXML($response->toXML());
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
		$od=$dom->saveXML();
		$xml = simplexml_load_string($od);
		$data1 = json_decode(json_encode($xml),TRUE);
		return $data1['ListOrderItemsResult']['OrderItems']['OrderItem'];
        //echo $dom->saveXML();
        //echo("ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");

     } catch (MarketplaceWebServiceOrders_Exception $ex) {
        echo("Caught Exception: " . $ex->getMessage() . "\n");
        echo("Response Status Code: " . $ex->getStatusCode() . "\n");
        echo("Error Code: " . $ex->getErrorCode() . "\n");
        echo("Error Type: " . $ex->getErrorType() . "\n");
        echo("Request ID: " . $ex->getRequestId() . "\n");
        echo("XML: " . $ex->getXML() . "\n");
        echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
		echo("<h1>发现错误，3秒后重试。。</h1>");
		echo "<script>function refreshPage() { window.location.reload(); } window.setTimeout('refreshPage()',3000);</script>";
		exit;
     }
 }

 function updatequantity($ordernum,$sku,$quantity){
	 global $db;
	 $is_has=$db->getValue("select count(*) from `quantity` where `ordernum` like '$ordernum' and `sku` like '$sku'");
	 if($is_has==0){
		$flag=$db->query("insert into `quantity` (`ordernum`,`sku`,`quantity`)values('$ordernum','$sku','$quantity')");
	 }else{
		$flag=$db->query("update `quantity` set `quantity`='$quantity' where `ordernum` like '$ordernum' and `sku` like '$sku'");
	 }
	 if($flag)echo "update quantity success<br>";
	 else echo "update quantity failture<br>";
	 return $flag;
 }